# waveplugs/eventnet.py
#
#

## gozerbot imports

from gozerlib.callbacks import callbacks
from gozerlib.utils.url import posturl, getpostdata
from gozerlib.persist.persist import PlugPersist
from gozerlib.commands import cmnds
from gozerlib.utils.exception import handle_exception
from gozerlib.xmpp.bot import XMPPBot

## simplejson imports

from waveapi.simplejson import dumps

## basic imports

import socket
import re

## VARS

outurl = "http://gozerbot.org:10102/eventnet/"
outxmpp = "waverelay@gozerbot.org"

state = PlugPersist('eventnet')

if not state.data:
    state.data = {}
if not state.data.has_key('relay'):
    state.data['relay'] = []

## callbacks

outbot = XMPPBot('eventnet-xmpp')

def preremote(bot, event):

    if event.channel in state.data['relay'] and not event.isremote:
        return True

def handle_doremote(bot, event):

    if event.isgae:
        outbot.say(outxmpp, event.tojson())
    else:
        posturl(outurl, {}, {'event': event.tojson() })

callbacks.add('BLIP_SUBMITTED', handle_doremote, preremote, threaded=True)
#outmonitor.add('eventnet', handle_doremote, preremote, threaded=True)

def handle_eventnet_on(bot, event):

    global state

    if not event.rest:
        target = event.channel
    else:
        target = event.rest

    if not target in state.data['relay']:
        state.data['relay'].append(target)
        state.save()

    event.done()

cmnds.add('eventnet-on', handle_eventnet_on, 'OPER')

def handle_eventnet_off(bot, event):

    global state

    if not event.rest:
        target = event.channel
    else:
        target = event.rest

    if target in state.data['relay']:
        state.data['relay'].remove(target)
        state.save()

    event.done()

cmnds.add('eventnet-off', handle_eventnet_off, 'OPER')

def handle_eventnet_list(bot, event):

    if not event.rest:
        target = event.channel
    else:
        target = event.rest

    event.reply("eventnet channels: ", state.data['relay'])

cmnds.add('eventnet-list', handle_eventnet_list, 'OPER')

